package javax.per.toolkit.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.per.toolkit.tools.Log;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Test for reading xml file with SAX<br/><br/>
 * <strong>Test code</strong><br/>
 * 		SAXReader sax=new SAXReader();<br/>
 *		sax.setXmlPath("src/aaa.xml");<br/>
 *		sax.init();<br/>
 *		sax.display();<br/>
 * @author yl34569
 */

public class SAXReader {
	
	private  String xmlPath=null;
	private SAXParser parser=null;
	TestHandler handler=null;
	
	/**
	 * 
	 * @param xmlPath
	 */
	public void setXmlPath(String xmlPath) {
		this.xmlPath = xmlPath;
	}

	/**
	 * 
	 * @param rootElement
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private  void createFile(String rootElement) throws Exception{
		File f=new File(xmlPath);
		if(f.exists())
			throw new Exception("xml file already exist");
		else{
			f.getParentFile().mkdirs();
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			FileOutputStream fos=new FileOutputStream(f);
			String content="<?xml version=\"1.0\" encoding=\"gbk\"?><"+rootElement+" />";
			fos.write(content.getBytes());
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @throws Exception
	 */
	public void init() throws Exception{
		SAXParserFactory factory=SAXParserFactory.newInstance();
		parser=factory.newSAXParser();
		if(xmlPath==null)
			throw new Exception("xml file path not set");
		if(!(new File(xmlPath).exists()))
			throw new Exception("xml file not exist");
		handler=new TestHandler();
	}
	
	
	/**
	 * 
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public void display() throws ParserConfigurationException, SAXException, IOException{
		File f=new File(xmlPath);
		parser.parse(f, handler);
	}

}


/**
 * 
 * @author yl34569
 *
 */
class TestHandler extends DefaultHandler{

	@Override
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		if(new String(arg0,arg1,arg2).trim().length()>0)
		Log.getLogger().debug(new String(arg0,arg1,arg2));
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException {
		
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
	}

	@Override
	public void startElement(String arg0, String arg1, String arg2,
			Attributes arg3) throws SAXException {
		super.startElement(arg0, arg1, arg2, arg3);
	}
	
}